<template>
  <div class="root">
    <div class="divBox">
      <div class="content-container">
        <div class="container">
          <el-row>
            <el-col :span="6">
              <div class="selectbox-root">
                <a class="selectbox-hint cursor-mi" style="width: 100px">账户类型</a>
                <div class="selectbox-deliver" />
                <el-cascader style="width: 120px" placeholder="全部" class="selectbox-input" v-model="selectedType"
                  :options="accountTypeDict" clearable @change="onClickSearch">
                </el-cascader>
              </div>
            </el-col>

            <el-col :span="5">
              <div style="margin-left: 16px" class="selectbox-root">
                <a class="selectbox-hint cursor-mi" style="width: 80px">状态</a>
                <div class="selectbox-deliver" />
                <el-cascader placeholder="全部" class="selectbox-input" v-model="selectedStatus"
                  :options="accountStatusDict" clearable @change="onClickSearch">
                </el-cascader>
              </div>
            </el-col>
            <el-col :span="5">
              <div style="margin-left: 16px" class="selectbox-root">
                <a class="selectbox-hint cursor-mi" style="width: 110px">产品版本</a>
                <div class="selectbox-deliver" />
                <el-cascader placeholder="全部" class="selectbox-input" v-model="selectedVersion"
                  :options="productVerssionDict" clearable @change="onClickSearch">
                </el-cascader>
              </div>
            </el-col>
            <el-col :span="8">
              <div style="margin-left: 10px; margin-right: 10px" class="selectbox-root">
                <a class="selectbox-hint cursor-mi" style="width: 140px">用户搜索</a>
                <div class="selectbox-deliver" />
                <el-input v-model="searchKeyWord" placeholder="输入用户名或公司名" clearable size="medium" @clear="onClickSearch"
                  @keyup.enter.native="onClickSearch" />
              </div>
            </el-col>
          </el-row>

          <button class="light-green-btn" @click="onClickSearch">查询</button>
        </div>
        <div>
          <button style="margin-top: 0px; margin-bottom: 20px; width: 103px" class="normal-white-btn" @click="addUser">
            +新增用户
          </button>
          <el-table :header-cell-style="{
            background: '#F2F5F7',
            border: '0px solid #DDDDDD',
            color: '#242B35',
            height: '64px',
          }" :show-header="true" :data="list" :row-style="{ height: '64px' }" :cell-style="cellStyle" stripe
            style="width: 100%; cursor: default" @row-click="clickItem">
            <el-table-column min-width="20"></el-table-column>
            <el-table-column label="用户账号" align="left" prop="accountName" min-width="120">
            </el-table-column>
            <el-table-column :show-overflow-tooltip="true" prop="username" label="用户名称" align="left" min-width="100" />
            <el-table-column align="left" prop="accountRole.roleNames[0]" label="用户角色" min-width="80" />
            <el-table-column align="left" prop="accountTypeName" label="账户类型" min-width="100" />
            <el-table-column align="left" prop="productVersionName" label="产品版本" min-width="100" />
            <el-table-column align="left" prop="accountStatusName" label="状态" min-width="60" />
            <el-table-column align="left" prop="createdTime" label="开户时间" min-width="120" />
            <el-table-column align="left" prop="validityPeriod" label="账户有效期" min-width="120" />
            <el-table-column align="left" prop="remarks" label="备注" min-width="60" />
            <el-table-column label="操作" min-width="150" align="center">
              <template slot-scope="scope">
                <a class="list-blue-text" v-on:click.stop="onEdit(scope.row)">编辑</a>
                <a style="margin-left: 10px" class="list-red-text" v-on:click.stop="onClickDelete(scope.row.id)">删除</a>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <div style="margin-top: 30px; margin-bottom: 10px" class="pageBox">
        <div style="flex-grow: 1" />
        <el-pagination style="margin: auto" background @size-change="handleSizeChange"
          @current-change="handleCurrentChange" :current-page="current" :page-size="pageSize" :page-count="pageCount"
          layout="total, sizes, prev, pager, next, jumper" :total="total">
        </el-pagination>
      </div>
    </div>
  </div>
</template>

<script>
import {
  accountList,
  getTenantInfo,
  adminList,
  updatedAccout,
  addAccount,
  delAccout,
  updatedTenant,
  getTenantList,
} from "@/api/systemadmin";
import selectDropDownBox from "@/components/selectbox/selectDropDownBox.vue";
import { openUrlInNewWindow } from "@/libs/OpenHelper";
import md5 from "js-md5";
import Cookies from "js-cookie";
import {
  getProductVerssionDict,
  getAccountStatusDict,
  getAccountTypeDict,
} from "@/config/dictHelper";
import { cursor } from "@/libs/element-table";

export default {
  name: "accountManager",
  components: { selectDropDownBox },
  data() {
    return {
      indeterminateFlag: false, //表头复选框状态
      reRender: true, // 重新渲染列表使用
      allchecked: false,
      searchKeyWord: "",
      selectedVersion: "", //被选中的版本
      selectedType: "", //被选中的类型
      selectedStatus: "", //被选中的状态
      list: [],
      visible: false,
      passwordTip: false, //密码提示
      tenantSelect: "", //选中的企业
      editFormVisible: false,
      total: 0,
      isSaved: false,
      tenant: {
        address: "",
        faxNumber: "",
        id: 0,
        industry: "",
        telephone: "",
        tenantName: "",
      },
      current: 0,
      password: "",
      roleOptions: [],
      addFormVisible: false,
      readFormVisible: false,
      pageCount: 1,
      optionStatus: [],
      pageSize: 10,
      tenantOptions: [],
      productVerssionDict: [], //产品版本字典
      accountStatusDict: [], //账户类型字典
      accountTypeDict: [], //账户类型字典
      addForm: {
        accountName: "",
        accountStatus: "",
        email: "",
        id: "",
        password: null,
        phone: "",
        username: "",
        remarks: "",
      },
      selectedRole: "",
      optionsOnlines: [
        {
          label: "全部",
        },
        {
          value: 1,
          label: "启用",
        },
        {
          value: 0,
          label: "禁用",
        },
      ],
      form: {
        accountName: "",
        accountStatus: "",
        email: "",
        id: 0,
        password: "",
        phone: "",
        remarks: "",
        username: "",
        roleIds: [],
      },
      value: "",
      roleList: [],
      tenantList: [], //租户列表
    };
  },
  watch: {},
  methods: {
    clickItem(row) {
      this.readFormVisible = true;
      this.tenant = {};
      this.selectedRole = row.accountRole.roleIds[0];
      this.addForm = row;
      for (var i in this.addForm) {
        if (this.addForm[i] == "--") {
          this.addForm[i] = "";
        }
      }
      if (row.tenantId != "--" && row.tenantId) {
        getTenantInfo(row.tenantId).then(
          (res) => {
            this.tenant = { ...res };
          },
          (err) => {
            this.$message.error(err.msgs);
          }
        );
      }
    },
    onCancel() {
      if (this.addForm.password) {
        if (this.isSaved) {
          this.editFormVisible = false;
        } else {
          this.$message.warning("您还未保存密码");
          this.isSaved = true;
        }
      } else {
        this.editFormVisible = false;
      }
    },
    confirmCancel() {
      this.visible = false;
      this.editFormVisible = false;
    },
    cellStyle({ row, column, rowIndex, columnIndex }) {
      if (column.label != "操作") {
        return "cursor:pointer;";
      }
    },
    /**
     * 作者:
     * 时间: 2022-05-30 16:07:51
     * 功能: 新增用户
     */
    addUser() {
      this.addFormVisible = true;
      this.readFormVisible = false;
      this.selectedRole = "";
    },
    /**
     * 作者:
     * 时间: 2022-06-06 14:27:17
     * 功能: 删除账户
     */
    onClickDelete(id) {
      this.$confirm("确认删除当前账户？").then((res) => {
        delAccout(id).then(
          (res) => {
            this.$message.success("删除成功");
            this.getList(1);
          },
          (err) => {
            this.$message.error(err.msg);
          }
        );
      });
    },
    /**
     * 作者:
     * 时间: 2022-06-02 15:18:47
     * 功能: 提交用户
     */
    addSubmit() {
      this.form.roleIds = [this.selectedRole];
      if (
        this.form.password &&
        this.form.accountName &&
        this.form.accountStatus &&
        this.form.phone
      ) {
        addAccount(this.form).then(
          (res) => {
            this.$message.success("添加成功");
            this.addFormVisible = false;
            this.getList(1);
          },
          (err) => {
            this.$message.error(err.msg);
          }
        );
      } else {
        this.$message.warning("必填项不能为空");
      }
    },
    /**
     * 作者:
     * 时间: 2022-05-30 15:18:05
     * 功能: 编辑账户
     */
    onEdit(row) {
      this.tenant = {};
      this.isSaved = false;
      this.editFormVisible = true;
      this.readFormVisible = false;
      this.selectedRole = row.accountRole.roleIds[0];
      this.addForm = row;
      for (var i in this.addForm) {
        if (this.addForm[i] == "--") {
          this.addForm[i] = "";
        }
      }
      this.addForm.accountStatus = row.accountStatus;
      if ( row.tenantId && row.tenantId != 0 && row.tenantId != "--") {
        getTenantInfo(row.tenantId).then(
          (res) => {
            this.tenant = { ...res };
            this.tenantSelect = this.tenant.tenantName;
          },
          (err) => {
            this.$message.error(err.msgs);
          }
        );
      } else {
      }
    },
    /**
     * 作者:
     * 时间: 2022-06-02 14:54:52
     * 功能: 提交保存
     */
    update() {
      if (this.passwordTip) {
        this.$message.warning("请检查两次输入的密码是否一致");
        return;
      }
      this.addForm.roleIds = [this.selectedRole];
      if (
        this.addForm.accountName &&
        this.addForm.phone &&
        this.addForm.roleIds &&
        this.addForm.accountType
      ) {
        let data = {
          accountName: this.addForm.accountName,
          accountStatus: this.addForm.accountStatus,
          accountType: this.addForm.accountType,
          createdTime: this.addForm.createdTime,
          email: this.addForm.email,
          id: this.addForm.id,
          password: this.addForm.password ? md5(this.addForm.password) : "",
          phone: this.addForm.phone,
          productVersion: this.addForm.productVersion,
          remarks: this.addForm.remarks,
          roleIds: this.addForm.roleIds,
          tenantId: this.tenant.id,
          username: this.addForm.username,
          validityPeriod: this.addForm.validityPeriod,
        };

        updatedAccout(data).then(
          (res) => {
            let JavaInfo = JSON.parse(Cookies.get("JavaInfo"));
            if (JavaInfo.accountId == this.addForm.id) {
              window.localStorage.setItem(
                "accountName",
                this.addForm.accountName
              );
              this.$store.dispatch("user/updateName", this.addForm.accountName);
            }
            this.$message.success("保存成功");
            this.isSaved = true;
            this.editFormVisible = false;
            this.getList(1);
          },
          (err) => {
            this.$message.error(err.msg);
          }
        );
      } else {
        this.$message.warning("必填项不能为空");
      }
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.getList(1);
    },
    handleCurrentChange(val) {
      this.current = val;
      this.getList(val);
    },
    // 监听页面宽度变化，刷新表格
    handleResize() {
      if (this.infoList) this.$refs.visitChart.handleResize();
    },
    onClickSearch() {
      const search = {
        current: this.current,
        size: this.pageSize,
        asc: true,
        keywords: this.searchKeyWord,
        accountType: Array.isArray(this.selectedType) ? this.selectedType[0] : this.selectedType,
        accountStatus: Array.isArray(this.selectedStatus) ? this.selectedStatus[0] : this.selectedStatus,
        productVersion: Array.isArray(this.selectedVersion) ? this.selectedVersion[0] : this.selectedVersion,
      };
      
      console.log("筛选参数:", search);
      console.log("当前筛选值:", {
        selectedType: this.selectedType,
        selectedStatus: this.selectedStatus,
        selectedVersion: this.selectedVersion,
        searchKeyWord: this.searchKeyWord
      });
      
      accountList(search).then(
        (res) => {
          console.log("搜索账户结果:", res);
          // 处理API响应数据结构
          const responseData = res.data || res;
          this.list = responseData.records || [];
          this.total = parseInt(responseData.total || 0);
          this.current = parseInt(responseData.current || 1);
          this.pageCount = Math.ceil(this.total / this.pageSize);
          this.list.map((v) => {
            //遍历表格数据
            for (var i in v) {
              v[i] = v[i] ? v[i] : "--";
              if (v[i] == " ") {
                v[i] = "--";
              }
            }
          });
        },
        (err) => {
          console.error("搜索账户失败:", err);
          this.$message.error(err.msg || "搜索失败");
        }
      );
    },
    onInputBlur() {
      if (this.password != this.addForm.password) {
        this.passwordTip = true;
      } else {
        this.passwordTip = false;
      }
    },
    getRoleList() {
      const data2 = {
        asc: true,
        size: 20,
        current: 1,
        // status: 1,
      };
      adminList(data2).then(
        (res) => {
          console.log("获取角色列表:", res);
          // 处理API响应数据结构
          const responseData = res.data || res;
          this.roleList = responseData.records || [];
          this.roleList.map((v) => {
            let role = { label: "", value: "" };
            role.label = v.roleName;
            role.value = v.id;
            this.roleOptions.push(role);
          });
        },
        (err) => {
          console.error("获取角色列表失败:", err);
          this.$message.error("获取角色列表失败: " + (err.response && err.response.data && err.response.data.message || err.message));
        }
      );
    },
    getList(page) {
      const data = {
        asc: true,
        size: this.pageSize,
        current: this.current,
        // status: 1,
      };
      accountList(data)
        .then((res) => {
          console.log("获取账户列表:", res);
          // 处理API响应数据结构
          const responseData = res.data || res;
          this.list = responseData.records || [];
          this.total = parseInt(responseData.total || 0);
          this.current = parseInt(responseData.current || 1);
          this.pageCount = Math.ceil(this.total / this.pageSize);
          this.list.map((v) => {
            //遍历表格数据
            for (var i in v) {
              v[i] = v[i] ? v[i] : "--";
              if (v[i] == " ") {
                v[i] = "--";
              }
            }
          });
        })
        .catch((error) => {
          console.error("获取账户列表失败:", error);
          this.$message.error("获取账户列表失败: " + (error.response && error.response.data && error.response.data.message || error.message));
        });
      getTenantList()
        .then((res) => {
          console.log("获取租户列表:", res);
          // 处理API响应数据结构
          const responseData = res.data || res;
          this.tenantList = responseData || [];
          this.tenantList.map((v) => {
            this.tenantOptions.push({ id: v.id, value: v.tenantName });
          });
          console.log(this.tenantList,111111111111111)
        })
        .catch((err) => {
          console.error("获取租户列表失败:", err);
          this.$message.error("获取租户列表失败");
        });
    },
    // 格式化产品版本字典
    formatProduct(data) {
      data.map((v) => {
        let CertificationItem = {
          label: "",
        };
        if (v.name == "全部") {
          CertificationItem.label = v.name;
          CertificationItem.value = "";
        } else {
          CertificationItem.value = v.value;
          CertificationItem.label = v.name;
        }
        this.productVerssionDict.push(CertificationItem);
      });
    },
    // 格式化状态字典
    formatStatus(data) {
      data.map((v) => {
        let CertificationItem = {
          label: "",
        };
        if (v.name == "全部") {
          CertificationItem.label = v.name;
          CertificationItem.value = "";
        } else {
          CertificationItem.value = v.value;
          CertificationItem.label = v.name;
        }
        this.accountStatusDict.push(CertificationItem);
      });
    },
    // 格式化类型字典
    formatType(data) {
      data.map((v) => {
        let CertificationItem = {
          label: "",
        };
        if (v.name == "全部") {
          CertificationItem.label = v.name;
          CertificationItem.value = "";
        } else {
          CertificationItem.value = v.value;
          CertificationItem.label = v.name;
        }
        this.accountTypeDict.push(CertificationItem);
      });
    },
    // 加载字典数据
    loadDictData() {
      try {
        // 加载账户状态字典
        const statusDict = getAccountStatusDict(this.$store);
        console.log("账户状态字典:", statusDict);
        if (statusDict && Array.isArray(statusDict) && statusDict.length > 0) {
          this.formatStatus(statusDict);
        } else {
          console.log("账户状态字典为空，使用默认数据");
        }
        
        // 加载账户类型字典
        const typeDict = getAccountTypeDict(this.$store);
        console.log("账户类型字典:", typeDict);
        if (typeDict && Array.isArray(typeDict) && typeDict.length > 0) {
          this.formatType(typeDict);
        } else {
          console.log("账户类型字典为空，使用默认数据");
        }
        
        // 加载产品版本字典
        const productDict = getProductVerssionDict(this.$store);
        console.log("产品版本字典:", productDict);
        if (productDict && Array.isArray(productDict) && productDict.length > 0) {
          this.formatProduct(productDict);
        } else {
          console.log("产品版本字典为空，使用默认数据");
        }
        
        // 如果任何字典为空，使用默认数据
        if (this.accountStatusDict.length === 0 || this.accountTypeDict.length === 0 || this.productVerssionDict.length === 0) {
          console.log("检测到空字典，加载默认数据");
          this.loadDefaultDictData();
        }
        
        console.log("字典数据加载完成:", {
          accountStatusDict: this.accountStatusDict,
          accountTypeDict: this.accountTypeDict,
          productVerssionDict: this.productVerssionDict
        });
      } catch (error) {
        console.error("加载字典数据失败:", error);
        // 如果字典数据加载失败，使用默认数据
        this.loadDefaultDictData();
      }
    },
    // 加载默认字典数据
    loadDefaultDictData() {
      // 默认账户状态
      this.accountStatusDict = [
        { label: "全部", value: "" },
        { label: "启用", value: "1" },
        { label: "禁用", value: "0" }
      ];
      
      // 默认账户类型 - 使用数据库中的实际值
      this.accountTypeDict = [
        { label: "全部", value: "" },
        { label: "管理员账户", value: "0380000001" },
        { label: "普通账户", value: "0380000002" },
        { label: "测试账户", value: "0380000003" }
      ];
      
      // 默认产品版本
      this.productVerssionDict = [
        { label: "全部", value: "" },
        { label: "企业版", value: "enterprise" },
        { label: "标准版", value: "standard" },
        { label: "专业版", value: "professional" },
        { label: "试用版", value: "trial" }
      ];
      
      console.log("已加载默认字典数据:", {
        accountStatusDict: this.accountStatusDict,
        accountTypeDict: this.accountTypeDict,
        productVerssionDict: this.productVerssionDict
      });
    },
    // 加载模拟账户数据
    loadMockAccountData() {
      const mockData = [
        {
          id: 1,
          accountName: "admin",
          username: "系统管理员",
          accountRole: {
            roleIds: [1],
            roleNames: ["系统管理员"]
          },
          accountTypeName: "管理员账户",
          productVersionName: "企业版",
          accountStatusName: "启用",
          createdTime: "2024-01-15 10:30:00",
          validityPeriod: "2025-01-15 10:30:00",
          remarks: "系统超级管理员账户",
          accountStatus: 1,
          accountType: "admin",
          productVersion: "enterprise",
          email: "admin@carbon.com",
          phone: "13800138000",
          tenantId: 1
        },
        {
          id: 2,
          accountName: "user001",
          username: "张三",
          accountRole: {
            roleIds: [2],
            roleNames: ["普通用户"]
          },
          accountTypeName: "普通账户",
          productVersionName: "标准版",
          accountStatusName: "启用",
          createdTime: "2024-02-20 14:20:00",
          validityPeriod: "2025-02-20 14:20:00",
          remarks: "普通用户账户",
          accountStatus: 1,
          accountType: "user",
          productVersion: "standard",
          email: "zhangsan@carbon.com",
          phone: "13800138001",
          tenantId: 2
        },
        {
          id: 3,
          accountName: "manager001",
          username: "李四",
          accountRole: {
            roleIds: [3],
            roleNames: ["部门经理"]
          },
          accountTypeName: "管理账户",
          productVersionName: "专业版",
          accountStatusName: "启用",
          createdTime: "2024-03-10 09:15:00",
          validityPeriod: "2025-03-10 09:15:00",
          remarks: "部门经理账户",
          accountStatus: 1,
          accountType: "manager",
          productVersion: "professional",
          email: "lisi@carbon.com",
          phone: "13800138002",
          tenantId: 3
        },
        {
          id: 4,
          accountName: "test001",
          username: "测试用户",
          accountRole: {
            roleIds: [4],
            roleNames: ["测试员"]
          },
          accountTypeName: "测试账户",
          productVersionName: "试用版",
          accountStatusName: "禁用",
          createdTime: "2024-04-05 16:45:00",
          validityPeriod: "2024-10-05 16:45:00",
          remarks: "测试专用账户",
          accountStatus: 0,
          accountType: "test",
          productVersion: "trial",
          email: "test@carbon.com",
          phone: "13800138003",
          tenantId: 4
        },
        {
          id: 5,
          accountName: "audit001",
          username: "王五",
          accountRole: {
            roleIds: [5],
            roleNames: ["审计员"]
          },
          accountTypeName: "审计账户",
          productVersionName: "企业版",
          accountStatusName: "启用",
          createdTime: "2024-05-12 11:30:00",
          validityPeriod: "2025-05-12 11:30:00",
          remarks: "审计专用账户",
          accountStatus: 1,
          accountType: "audit",
          productVersion: "enterprise",
          email: "wangwu@carbon.com",
          phone: "13800138004",
          tenantId: 5
        }
      ];
      
      this.list = mockData;
      this.total = mockData.length;
      this.current = 1;
      this.pageCount = Math.ceil(this.total / this.pageSize);
      
      // 处理数据格式
      this.list.map((v) => {
        for (var i in v) {
          v[i] = v[i] ? v[i] : "--";
          if (v[i] == " ") {
            v[i] = "--";
          }
        }
      });
      
      this.$message.info("已加载模拟账户数据");
    },
    // 加载模拟角色数据
    loadMockRoleData() {
      const mockRoles = [
        { id: 1, roleName: "系统管理员" },
        { id: 2, roleName: "普通用户" },
        { id: 3, roleName: "部门经理" },
        { id: 4, roleName: "测试员" },
        { id: 5, roleName: "审计员" }
      ];
      
      this.roleList = mockRoles;
      this.roleOptions = [];
      mockRoles.map((v) => {
        let role = { label: "", value: "" };
        role.label = v.roleName;
        role.value = v.id;
        this.roleOptions.push(role);
      });
      
      console.log("已加载模拟角色数据:", this.roleOptions);
    },
  },
  // checkbox end
  created() {
    // this.handleChangeVisitType();

  },
  mounted() {
    this.getList(1);
    this.getRoleList();
    this.loadDictData();
    
    // 确保筛选器有选项，如果没有则使用默认数据
    this.$nextTick(() => {
      if (this.accountStatusDict.length === 0 || this.accountTypeDict.length === 0 || this.productVerssionDict.length === 0) {
        console.log("检测到空筛选器，强制加载默认数据");
        this.loadDefaultDictData();
      }
    });
  },
};
</script>

<style lang="scss" scoped>
.root {
  background: #f2f5f7;
}

.divBox {
  margin: 20px;
  background: #ffffff;
  box-shadow: 0px 2px 8px 0px #eaf0f3;
  border-radius: 8px;
}

.container {
  margin: 20px 0px 20px 0px;
  display: flex;
  flex-direction: row;
}

.content-container {
  display: flex;
  flex-direction: column;
  width: 100%;
}

>>>.el-cascader .el-input .el-input__inner,
>>>.el-cascader .el-input.is-focus .el-input__inner {
  border-color: transparent;
}

.acea-row {
  /deep/.el-avatar--small {
    width: 22px;
    height: 22px;
    line-height: 22px;
  }
}

.checkTime {
  /deep/.el-radio__input {
    display: none;
  }
}

.ivu-pl-8 {
  margin-left: 8px;
  font-size: 14px;
}

.dashboard-console-visit {
  /deep/.el-card__header {
    padding: 14px 20px !important;
  }

  ul {
    li {
      list-style-type: none;
      margin-top: 12px;
    }
  }
}

.ivu-mb {
  margin-bottom: 10px;
}

.newsImg {
  width: 30px;
  height: 30px;
  border-radius: 4px;
}

.table-text {
  position: relative;
  top: 10px;
}

.require {
  color: red;
  font-size: 16px;
}

.cursor-mi {
  cursor: default;
}
</style>
